const WXAPI = require('apifm-wxapi')

//登陆
async function register(page, data, backUrl) {
  let iv = data.iv;
  let encryptedData = data.encryptedData;
  // 获取新的 code  避免手机号解码失败
  wx.login({
    success: (result) => {
      wx.setStorageSync('code', result.code)
      // console.log('code', result.code);
      //后端登录接口
      WXAPI.login_wx({
        code: result.code,
        encryptedData: encryptedData,
        iv: iv,
      }).then(function (res) {
        // console.log("WXAPI.login_wx:", res);
        if (res.code === 200) {
          if (res.data.appToken) {
            //token
            wx.setStorageSync('appToken', res.data.appToken)
            //角色
            wx.setStorageSync('miniAppRole', 'Waiter')
          } else {
            //角色
            wx.setStorageSync('miniAppRole', 'Customer')
          }
          //手机号
          if (res.data.phoneNum) {
            wx.setStorageSync('phoneNumber', res.data.phoneNum);
            // console.log("phoneNumber", res.data.phoneNum);
          }
          //用户信息
          if (res.data.user && res.data.company) {
            wx.setStorageSync('userInfo', {
              user: res.data.user,
              company: res.data.company,
            })
            //用户公司ID
            wx.setStorageSync('myCompanyId', res.data.company.id)
            wx.setStorageSync('userId', res.data.user.userId)
          }
          //从分享页跳转
          if (backUrl) {
            wx.removeStorageSync('backUrl')
            wx.navigateTo({
              url: backUrl,
            })
          } else {
            page.onShow()
          }
        } else {
          wx.showModal({
            title: '登录失败',
            content: res.msg,
            showCancel: false
          })
          wx.login({
            success(res) {
              wx.setStorageSync('code', res.code)
            }
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showModal({
          title: '无法登录',
          showCancel: false
        })
      })
    }
  })

}


module.exports = {
  register: register,
}